/**
 * #### 导航标签自动高亮
 * @param {HTMLElement|string} id
 * @returns
 */
function highLight(id) {
  // 获取所有class为hightlight的a标签，并移除它们的hightlight类
  document
    .querySelectorAll("a.hightlight")
    .forEach((a) => a.classList.remove("hightlight"));
  // 如果id是一个HTMLElement对象，则给它添加hightlight类
  if (id instanceof HTMLElement) {
    id.classList.add("hightlight");
    return;
  }
  // 如果id是一个字符串，并且以#开头，则去掉#号
  if (typeof id === "string" && id.startsWith("#")) {
    id = id.substring(1);
  }
  // 获取href属性为#id的a标签，并给它添加hightlight类
  document.querySelector(`a[href="#${id}"]`).classList.add("hightlight");
}

function debounce(fn, delay) {
  let timer = null;
  return function () {
    if (timer) {
      clearTimeout(timer);
      timer = null;
    }
    timer = setTimeout(() => {
      fn.apply(this, arguments);
    }, delay);
  };
}
const titles = [],
  topRange = 300;

const links = document.querySelectorAll(".toc a[href^='#']");
for (const link of links) {
  link.addEventListener("click", () => {
    highLight(link);
  });
  const url = new URL(link.href);
  const dom = document.querySelector(url.hash);
  if (dom) {
    titles.push(dom);
  }
}

// 定义一个滚动处理函数
const scrollHandler = debounce(() => {
  // 获取所有标题的rect
  const rects = titles.map((dom) => dom.getBoundingClientRect());
  // 遍历所有标题
  for (let i = 0; i < rects.length; i++) {
    const title = titles[i]; //标题dom
    const rect = rects[i]; //标题dom的rect
    // 判断标题是否在可视区域内
    if (
      (rect.top >= 0 && rect.top <= topRange) ||
      (rect.top < 0 &&
        rects[i + 1] &&
        rects[i + 1].top >= document.documentElement.clientHeight)
    ) {
      // 如果在可视区域内，则高亮显示
      highLight(title.id);
      break;
    }
  }
}, 100);

window.addEventListener("scroll", scrollHandler);
